<template>
  <div class="case-management">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-6 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-800">案件管理</h1>
          <div class="flex items-center space-x-4">
            <el-button type="primary" @click="createNewCase">
              <i class="fas fa-plus mr-2"></i>新建案件
            </el-button>
            <el-button @click="refreshCases">
              <i class="fas fa-sync-alt mr-2"></i>刷新
            </el-button>
          </div>
        </div>
      </div>
    </header>

    <!-- 统计卡片 -->
    <div class="stats-section bg-gray-50 py-6">
      <div class="container mx-auto px-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div class="stat-card bg-white rounded-lg p-6 shadow-sm">
            <div class="flex items-center">
              <div class="stat-icon bg-blue-100 p-3 rounded-full">
                <i class="fas fa-folder text-blue-600 text-xl"></i>
              </div>
              <div class="ml-4">
                <p class="text-sm text-gray-600">总案件数</p>
                <p class="text-2xl font-bold text-gray-800">{{ caseStats.total }}</p>
              </div>
            </div>
          </div>
          
          <div class="stat-card bg-white rounded-lg p-6 shadow-sm">
            <div class="flex items-center">
              <div class="stat-icon bg-yellow-100 p-3 rounded-full">
                <i class="fas fa-clock text-yellow-600 text-xl"></i>
              </div>
              <div class="ml-4">
                <p class="text-sm text-gray-600">待处理</p>
                <p class="text-2xl font-bold text-gray-800">{{ caseStats.pending }}</p>
              </div>
            </div>
          </div>
          
          <div class="stat-card bg-white rounded-lg p-6 shadow-sm">
            <div class="flex items-center">
              <div class="stat-icon bg-green-100 p-3 rounded-full">
                <i class="fas fa-play text-green-600 text-xl"></i>
              </div>
              <div class="ml-4">
                <p class="text-sm text-gray-600">进行中</p>
                <p class="text-2xl font-bold text-gray-800">{{ caseStats.inProgress }}</p>
              </div>
            </div>
          </div>
          
          <div class="stat-card bg-white rounded-lg p-6 shadow-sm">
            <div class="flex items-center">
              <div class="stat-icon bg-gray-100 p-3 rounded-full">
                <i class="fas fa-check text-gray-600 text-xl"></i>
              </div>
              <div class="ml-4">
                <p class="text-sm text-gray-600">已结案</p>
                <p class="text-2xl font-bold text-gray-800">{{ caseStats.closed }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section bg-white border-b border-gray-200 py-4">
      <div class="container mx-auto px-6">
        <div class="flex flex-wrap items-center gap-4">
          <el-select v-model="filters.status" placeholder="案件状态" clearable class="w-40">
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="进行中" value="in-progress"></el-option>
            <el-option label="已结案" value="closed"></el-option>
          </el-select>
          
          <el-select v-model="filters.type" placeholder="案件类型" clearable class="w-40">
            <el-option label="诉讼" value="litigation"></el-option>
            <el-option label="调解" value="settlement"></el-option>
          </el-select>
          
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="w-60"
          ></el-date-picker>
          
          <el-input
            v-model="searchKeyword"
            placeholder="智能搜索：支持案件编号、姓名、拼音、关键词分词等"
            class="w-80"
            clearable
          >
            <template #prefix>
              <i class="fas fa-search text-gray-400"></i>
            </template>
          </el-input>
          
          <el-input
            v-model="filters.memoKeyword"
            placeholder="备忘录专项搜索"
            class="w-60"
            clearable
          >
            <template #prefix>
              <i class="fas fa-sticky-note text-gray-400"></i>
            </template>
          </el-input>
          
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="clearFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 案件列表 -->
    <div class="case-list-section bg-gray-50 min-h-screen py-6">
      <div class="container mx-auto px-6">
        <div class="bg-white rounded-lg shadow-sm">
          <div class="p-6 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-800">案件列表</h2>
          </div>
          
          <el-table :data="filteredCases" style="width: 100%" v-loading="loading">
            <el-table-column prop="caseNumber" label="案件编号" width="150">
              <template #default="scope">
                <span class="font-medium text-blue-600 cursor-pointer" @click="viewCase(scope.row)">
                  {{ scope.row.caseNumber }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column prop="clientName" label="当事人" width="120"></el-table-column>
            
            <el-table-column prop="caseType" label="案件类型" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.caseType === 'litigation' ? 'danger' : 'success'">
                  {{ scope.row.caseType === 'litigation' ? '诉讼' : '调解' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="lawyer" label="承办律师" width="120"></el-table-column>
            
            <el-table-column prop="createdAt" label="创建时间" width="150">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="progress" label="进度" width="200">
              <template #default="scope">
                <el-progress 
                  :percentage="scope.row.progress" 
                  :color="getProgressColor(scope.row.progress)"
                  :stroke-width="8"
                ></el-progress>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewCase(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="editCase(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCase(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="p-6 border-t border-gray-200">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建案件对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建案件" width="60%">
      <el-form :model="newCase" :rules="caseRules" ref="caseForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="案件编号" prop="caseNumber">
              <el-input v-model="newCase.caseNumber" placeholder="请输入案件编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案件类型" prop="caseType">
              <el-select v-model="newCase.caseType" placeholder="请选择案件类型" style="width: 100%">
                <el-option label="诉讼" value="litigation"></el-option>
                <el-option label="调解" value="settlement"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当事人姓名" prop="clientName">
              <el-input v-model="newCase.clientName" placeholder="请输入当事人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="clientPhone">
              <el-input v-model="newCase.clientPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="案件描述" prop="description">
          <el-input 
            v-model="newCase.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入案件描述"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewCase">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCaseStore } from '@/stores/case'
import { caseApi } from '@/api/case'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CaseManagement',
  setup() {
    const router = useRouter()
    const caseStore = useCaseStore()
    
    // 响应式数据
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const searchKeyword = ref('')
    const createDialogVisible = ref(false)
    
    const filters = reactive({
      status: '',
      type: '',
      dateRange: [],
      memoKeyword: ''
    })
    
    const newCase = reactive({
      caseNumber: '',
      caseType: '',
      clientName: '',
      clientPhone: '',
      description: ''
    })
    
    const caseRules = {
      caseNumber: [{ required: true, message: '请输入案件编号', trigger: 'blur' }],
      caseType: [{ required: true, message: '请选择案件类型', trigger: 'change' }],
      clientName: [{ required: true, message: '请输入当事人姓名', trigger: 'blur' }],
      clientPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
    }
    
    // 计算属性
    const caseStats = computed(() => caseStore.caseStats)
    
    const filteredCases = computed(() => {
      let cases = caseStore.getFilteredCases()
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        cases = cases.filter(case_ => {
          // 基础字段搜索
          const basicMatch = 
            case_.caseNumber.toLowerCase().includes(keyword) ||
            case_.clientName.toLowerCase().includes(keyword) ||
            (case_.memo && case_.memo.toLowerCase().includes(keyword))
          
          // 拼音搜索支持（简单的首字母匹配）
          const pinyinMatch = case_.clientName.match(/[\u4e00-\u9fa5]/g)?.some(char => {
            const pinyin = getPinyin(char)
            return pinyin.toLowerCase().startsWith(keyword)
          })
          
          // 部分匹配和容错搜索
          const fuzzyMatch = 
            case_.caseNumber.replace(/[-_]/g, '').toLowerCase().includes(keyword.replace(/[-_]/g, '')) ||
            case_.clientName.replace(/\s/g, '').toLowerCase().includes(keyword.replace(/\s/g, ''))
          
          // 关键词分词搜索
          const words = keyword.split(/\s+/).filter(word => word.length > 0)
          const wordMatch = words.every(word => 
            case_.caseNumber.toLowerCase().includes(word) ||
            case_.clientName.toLowerCase().includes(word) ||
            (case_.memo && case_.memo.toLowerCase().includes(word))
          )
          
          return basicMatch || pinyinMatch || fuzzyMatch || wordMatch
        })
      }
      
      if (filters.memoKeyword) {
        const memoKeyword = filters.memoKeyword.toLowerCase()
        cases = cases.filter(case_ => 
          case_.memo && case_.memo.toLowerCase().includes(memoKeyword)
        )
      }
      
      return cases
    })
    
    // 模拟案件数据
    const mockCases = [
      {
        id: 1,
        caseNumber: 'CASE-2024-001',
        clientName: '张三',
        caseType: 'litigation',
        status: 'in-progress',
        lawyer: '李律师',
        createdAt: '2024-01-15',
        progress: 75,
        memo: '客户在北京六院治疗，需要关注伤残鉴定时间安排'
      },
      {
        id: 2,
        caseNumber: 'CASE-2024-002',
        clientName: '王五',
        caseType: 'settlement',
        status: 'pending',
        lawyer: '张律师',
        createdAt: '2024-01-10',
        progress: 30,
        memo: '保险公司理赔金额存在争议，需要准备补充材料'
      },
      {
        id: 3,
        caseNumber: 'CASE-2024-003',
        clientName: '赵六',
        caseType: 'litigation',
        status: 'closed',
        lawyer: '王律师',
        createdAt: '2024-01-05',
        progress: 100,
        memo: '案件已顺利结案，客户满意度较高'
      },
      {
        id: 4,
        caseNumber: 'CASE-2024-004',
        clientName: '孙七',
        caseType: 'settlement',
        status: 'in-progress',
        lawyer: '李律师',
        createdAt: '2024-01-08',
        progress: 60,
        memo: '需要联系医院获取完整病历，下周二提醒客户'
      },
      {
        id: 5,
        caseNumber: 'CASE-2024-005',
        clientName: '周八',
        caseType: 'litigation',
        status: 'pending',
        lawyer: '赵律师',
        createdAt: '2024-01-12',
        progress: 20,
        memo: '交通事故现场证据收集不全，需要调取监控录像'
      }
    ]

    // 拼音搜索辅助函数
    const getPinyin = (char) => {
      const pinyinMap = {
        '张': 'zhang', '王': 'wang', '李': 'li', '赵': 'zhao', '陈': 'chen', 
        '刘': 'liu', '杨': 'yang', '黄': 'huang', '周': 'zhou', '吴': 'wu',
        '徐': 'xu', '孙': 'sun', '马': 'ma', '朱': 'zhu', '胡': 'hu',
        '郭': 'guo', '何': 'he', '高': 'gao', '林': 'lin', '罗': 'luo'
      }
      return pinyinMap[char] || char
    }

    // 方法
    const getCases = async () => {
      loading.value = true
      try {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 使用模拟数据
        caseStore.setCaseList(mockCases)
        total.value = mockCases.length
        
        ElMessage.success('案件列表加载成功')
      } catch (error) {
        ElMessage.error('获取案件列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const refreshCases = () => {
      getCases()
    }
    
    const applyFilters = () => {
      caseStore.setFilters(filters)
      currentPage.value = 1
      getCases()
    }
    
    const clearFilters = () => {
      Object.assign(filters, {
        status: '',
        type: '',
        dateRange: [],
        memoKeyword: ''
      })
      searchKeyword.value = ''
      caseStore.setFilters({})
      currentPage.value = 1
      getCases()
    }
    
    const createNewCase = () => {
      createDialogVisible.value = true
    }
    
    const submitNewCase = async () => {
      try {
        // 模拟创建案件
        const newCaseData = {
          id: Date.now(),
          caseNumber: newCase.caseNumber,
          clientName: newCase.clientName,
          caseType: newCase.caseType,
          status: 'pending',
          lawyer: '当前律师',
          createdAt: new Date().toISOString().split('T')[0],
          progress: 0
        }
        
        mockCases.unshift(newCaseData)
        
        ElMessage.success('案件创建成功')
        createDialogVisible.value = false
        getCases()
        
        // 重置表单
        Object.assign(newCase, {
          caseNumber: '',
          caseType: '',
          clientName: '',
          clientPhone: '',
          description: ''
        })
      } catch (error) {
        ElMessage.error('案件创建失败')
      }
    }
    
    const viewCase = (case_) => {
      caseStore.setCurrentCase(case_)
      router.push(`/lawyer/case/${case_.id}`)
    }
    
    const editCase = (case_) => {
      router.push(`/lawyer/case/${case_.id}/edit`)
    }
    
    const deleteCase = async (case_) => {
      try {
        await ElMessageBox.confirm('确定要删除这个案件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 模拟删除案件
        const index = mockCases.findIndex(c => c.id === case_.id)
        if (index > -1) {
          mockCases.splice(index, 1)
        }
        
        ElMessage.success('案件删除成功')
        getCases()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('案件删除失败')
        }
      }
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      getCases()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getCases()
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'warning',
        'in-progress': 'primary',
        'closed': 'success'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'in-progress': '进行中',
        'closed': '已结案'
      }
      return statusMap[status] || '未知'
    }
    
    const getProgressColor = (progress) => {
      if (progress < 30) return '#f56c6c'
      if (progress < 70) return '#e6a23c'
      return '#67c23a'
    }
    
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }
    
    onMounted(() => {
      getCases()
    })
    
    return {
      loading,
      currentPage,
      pageSize,
      total,
      searchKeyword,
      filters,
      createDialogVisible,
      newCase,
      caseRules,
      caseStats,
      filteredCases,
      refreshCases,
      applyFilters,
      clearFilters,
      createNewCase,
      submitNewCase,
      viewCase,
      editCase,
      deleteCase,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      getProgressColor,
      formatDate
    }
  }
}
</script>

<style scoped>
.case-management {
  min-height: 100vh;
  background-color: #f9fafb;
}

.stat-card {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 